﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Xml;
using System.Text;
using System.Xml.Linq;
using System.Data;
using System.Net;
using System.Web.Script.Serialization;
using Cms.Common;

public partial class shop_login : System.Web.UI.Page
{
    public class SmsApi
    {

        public string rescode { get; set; }

        public string message { get; set; }

    }
    
    protected void Page_Load(object sender, EventArgs e)
    {
        
        if (!IsPostBack)
        {
            string redirectUrl = Request.Url.ToString();
            Cms.BLL.wx_info info = new Cms.BLL.wx_info();
            string appid = info.GetModel(1).AppId;
            string appsecret = info.GetModel(1).AppSecret;

            if (Request.QueryString["code"] != null && Request.QueryString["code"] != "")
            {

                string Code = Request.QueryString["code"].ToString();
                string result = wxuserinfo.getwxCode(Code, redirectUrl);
                HiddenField1.Value = result;
                Session["user_openid"] = result;
              
            }
            else
            {
                string posturl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + redirectUrl + "&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect ";
		            //string posturl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + redirectUrl + "&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect ";//&scope=snsapi_base
                Response.Redirect(posturl);
            }
        }
    }
    public void bind_date()
    {
      
    }
  

    #region 发送短信==============
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        this.Session["Verification_code"] = Cms.Common.Utils.Number(6);//随机生成6位数字
        string telphone = telPhone.Value.Trim();
        string content = "您当前的手机验证码：" + this.Session["Verification_code"].ToString();

        Cms.BLL.C_sms bll = new Cms.BLL.C_sms();
        Cms.Model.C_sms model = new Cms.Model.C_sms();
        model.name = "";//名字
        model.telphone = telphone;//手机号码
        model.content = content;//内容
        model.state = 0;//发送状态
        model.updateTime = Convert.ToDateTime(Cms.Common.ManagementInfo.GetTime());//时间
        int result = bll.Add(model);
        if (result > 0)
        {
            string smsResult = adminUser.Sms(telphone, content);
            SmsApi p = Cms.Common.Utils.JsonDeserialize<SmsApi>(smsResult);
            if (p.rescode == "0")
            {
                int counts = Cms.DBUtility.DbHelperSQL.ExecuteSql("update C_sms set state=1 where id=" + result);//修改状态
                //JscriptMsg("验证码发送成功！", "NotJump", "Success");
                ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "JsPrint", "parent.jsprintWeb(\"验证码发送成功！\", \"NotJump\", \"Success\")", true);
            }
            else
            {
                ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "JsPrint", "parent.jsprintWeb(\"验证码发送失败！\", \"NotJump\", \"Error\")", true);
                //JscriptMsg("验证码发送失败！", "NotJump", "Error");
            }
        }
    }
    #endregion


    #region 会员登录=======================
    protected void Button1_Click(object sender, EventArgs e)
    {
        Cms.BLL.C_user cuser = new Cms.BLL.C_user();
        Cms.Model.C_user muser = new Cms.Model.C_user();
        string tel_phone = telPhone.Value.Trim();
        if (!cuser.Exists(tel_phone))
        {
            ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "JsPrint", "jsprintWeb(\"该手机号未注册过！\", \"NotJump\", \"Error\")", true);
            return;
        }
        //if (this.Session["Verification_code"].ToString() != VerificationCode.Value.Trim())
        //{
        //    ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "JsPrint", "jsprintWeb(\"验证码不正确！\", \"NotJump\", \"Error\")", true);
        //    //JscriptMsg("验证码不正确！", "NotJump", "Error");
        //    return;
        //}
        DataTable dt_user = cuser.GetList("telphone='" + tel_phone + "'").Tables[0];
        if (dt_user != null && dt_user.Rows.Count > 0)
        {
            int id = Convert.ToInt32(dt_user.Rows[0]["id"]);

            if (dt_user.Rows[0]["openid"].ToString() == Session["user_openid"].ToString())
            {
                DataTable dt = new Cms.BLL.wx_userinfo().GetList("openid='" + Session["user_openid"].ToString() + "' order by updatetime desc").Tables[0];
                if (dt != null && dt.Rows.Count > 0)
                {
                    muser = new Cms.BLL.C_user().GetModel(id);
                    muser.openid = Session["user_openid"].ToString();
                    muser.headimgurl = dt.Rows[0]["headimgurl"].ToString();
                    muser.username = dt.Rows[0]["nickname"].ToString();
                    new Cms.BLL.C_user().Update(muser);
                }
                //写入session Session["user_openid"].ToString() == dt_user.Rows[0]["openid"].ToString()
                Session["user_id"] = id;//保存session 用户ID
                //写入Cookie
                HttpCookie cookie = new HttpCookie("user");//创建Cookie
                cookie["user_id"] = id.ToString();//保存Cookie 用户ID
                cookie.Expires = DateTime.Now.AddHours(14400);
                Response.Cookies.Add(cookie);
                adminUser.AddUserLog(Cms.Common.DTEnums.ActionEnum.Login.ToString(), "用户登录");
                ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "JsPrint", "location.href='/shop/main.aspx'", true);
            }
            else
            {
                //muser = new Cms.BLL.C_user().GetModel(id);
                //muser.openid = Session["user_openid"].ToString();
                //DataTable dt = new Cms.BLL.wx_userinfo().GetList("openid='" + Session["user_openid"].ToString() + "' order by updatetime desc").Tables[0];
                //if (dt != null && dt.Rows.Count > 0)
                //{
                //    muser.openid = Session["user_openid"].ToString();
                //    muser.headimgurl = dt.Rows[0]["headimgurl"].ToString();
                //    muser.username = dt.Rows[0]["nickname"].ToString();
                //}
                //new Cms.BLL.C_user().Update(muser);
                ////写入session
                //Session["user_id"] = id;//保存session 用户ID
                ////写入Cookie
                //HttpCookie cookie = new HttpCookie("user");//创建Cookie
                //cookie["user_id"] = id.ToString();//保存Cookie 用户ID
                //cookie.Expires = DateTime.Now.AddHours(14400);
                //Response.Cookies.Add(cookie);
                adminUser.AddUserLog(Cms.Common.DTEnums.ActionEnum.Login.ToString(), "您登录的微信账号不匹配");
                //ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "JsPrint", "location.href='/shop/main.aspx'", true);
               
                ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "JsPrint", "jsprintWeb(\"您登录的手机号码与微信账号不匹配！\", \"NotJump\", \"Error\")", true);
            }
        }
        else
        {
            ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "JsPrint", "jsprintWeb(\"会员不存在！\", \"NotJump\", \"Error\")", true);
        }

    }
    #endregion

    #region 提示框=================================
    public void JscriptMsg(string msgtitle, string url, string msgcss)
    {
        string msbox = "";
        if (url == "back")
        {
            msbox = "parent.jsdialog(\"提示\", \"" + msgtitle + "\",\"" + url + "\", \"\", \"" + msgcss + "\")";
            ClientScript.RegisterClientScriptBlock(Page.GetType(), "JsPrint", msbox, true);
        }
        else
        {
            msbox = "parent.jsprintWeb(\"" + msgtitle + "\", \"" + url + "\", \"" + msgcss + "\")";
            ClientScript.RegisterClientScriptBlock(Page.GetType(), "JsPrint", msbox, true);
        }

    }
    #endregion

    protected void Button2_Click(object sender, EventArgs e)
    {
        Response.Redirect("newUser.aspx");
    }
}